﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ArchiveIISLogs
{
    public class AppLogger
    {
        const string Tab = "\t";
        const string LogFileNameFormat = "ArchiveIISLogs-{0}.txt";

        //log an action to the log dir.
        public static void LogMessage(string message)
        {
            string logFileName = System.IO.Path.Combine(System.Environment.CurrentDirectory, LogFileNameFormat.FormatWith(GetMonthlyLogFileName()));
            string textToWrite = GetNowFormattedDateTime() + Tab + message;

            WriteToFile(logFileName, textToWrite);
        }

        private static void WriteToFile(string fullFilePath, string textToWrite)
        {
            if (!Directory.Exists(Path.GetDirectoryName(fullFilePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(fullFilePath));
            }

            using (StreamWriter sw = new StreamWriter(fullFilePath, true))
            {
                sw.WriteLine(textToWrite);
            }
        }

        private static string GetNowFormattedDateTime()
        {
            return (DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()).Replace("/", "-");
        }

        private static string GetMonthlyLogFileName()
        {
            //currently using a Year-Month structure for naming the logfiles. one log file per day would result in too many files.
            return DateTime.Now.Year + "-" + DateTime.Now.ToString("MM");
        }
    }
}
